package com.by.modules.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.by.common.api.CommonResult;
import com.by.config.security.JwtTokenUtil;
import com.by.modules.dto.UmsAdminDto;
import com.by.modules.mapper.UmsAdminMapper;
import com.by.modules.pojo.UmsAdmin;
import com.by.modules.service.IUmsAdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author yufei
 * @since 2021-11-10
 */
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements IUmsAdminService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UmsAdminMapper adminMapper;


    @Override
    public CommonResult register(UmsAdminDto dto) {
        // 判断dto是否为空
        if (null == dto) {
            return CommonResult.validateFailed("请输入您的信息");
        }
        // 用户名和密码必须传进来
        if (StringUtils.isBlank(dto.getUsername()) || StringUtils.isBlank(dto.getPassword())) {
            return CommonResult.validateFailed("请输入用户名或密码");
        }
        // 用户名邮箱不能重复
        QueryWrapper<UmsAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(wrapper->wrapper.eq("username",dto.getUsername()).
                or().eq(StringUtils.isNotBlank(dto.getEmail()),"email",dto.getEmail()));
        List<UmsAdmin> umsAdminList = adminMapper.selectList(queryWrapper);
        if (umsAdminList.size() == 0) {
            // 将密码进行加密操作
            String hashpw = BCrypt.hashpw(dto.getPassword());
            dto.setPassword(hashpw);
            // 将Date类型的日期转换为LocalDateTime类型
            Instant instant = new Date().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            UmsAdmin admin = new UmsAdmin();
            //将dto的值 赋值给admin
            BeanUtils.copyProperties(dto,admin);
            admin.setCreateTime(localDateTime);
            admin.setLoginTime(localDateTime);
            admin.setStatus(setStatus(1));
            adminMapper.insert(admin);
            return CommonResult.success(admin,"注册成功");
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 将int类型的状态转换为boolean类型
     * @param i
     * @return
     */
    private Boolean setStatus(int i) {
        Boolean result;
        result = i > 0 ? true : false;
        return result;
    }
    /**
     * 登录之后返回token
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public CommonResult login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
            return CommonResult.failed("验证码输入有误，请重新输入！");
        }
        // 登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null == userDetails || !passwordEncoder.matches(password,userDetails.getPassword())) {
            return CommonResult.validateFailed("用户名或密码错误！");
        }
        if (!userDetails.isEnabled()) {
            return CommonResult.forbidden("账号被禁用，请联系管理员！");
        }
        // 更新security登陆用户对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails,
                        null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return CommonResult.success(tokenMap,"登陆成功");
    }

    @Override
    public UmsAdmin getAdminByUsername(String username) {
        return adminMapper.selectOne(new QueryWrapper<UmsAdmin>().eq("username",username)
                /*.eq("enabled",true)*/);
    }
}
